import { chattingList, historyList } from '@/api/msg';
import { getToken } from '@/utils/auth';
import router from '@/router';

const state = {
    history: [],
    chatting: [],
    currentChat: {},
    webSock: null,
    lockReconnect: false, //避免重复连接
    timer: null,
    token: getToken(),
    random: 0,
    wsStatus: false
};

const mutations = {
  SET_HISTORY: (state, history) => {
    console.log('fff', history)
    state.history = history;
  },
  SET_CHATTING: (state, chatting) => {
    state.chatting = chatting;
  },
  SET_CURRENTCHAT(state, currentChat){
    state.currentChat = currentChat;
  },
  SET_lockReconnect(state, lockReconnect){
    state.lockReconnect = lockReconnect;
  },
  SET_webSock(state, webSock){
    state.webSock = webSock
  }
};

const actions = {
    getChatting({ commit, state }){
      chattingList().then(res=>{
        console.log("会话列表", res)
        commit("SET_CHATTING", res)
        state.random = Math.random()
      })
    },

    getHistory({ commit }, params){
      console.log("lll", params)
      return new Promise((resolve, reject) => {
        historyList(params).then(res=>{
          commit("SET_HISTORY",res.list)
          console.log("聊天记录", res.list.reverse())
          resolve(res)
        }).catch(err=>{
          reject(err)
        })
      })
    },

    // 连接ws
    initwebsocket({ commit, state, dispatch  }, token){
        if (state.lockReconnect) return;
        commit("SET_lockReconnect", true)
        commit("SET_webSock", new WebSocket(`${process.env.VUE_APP_SOCKET_API}`))
        state.webSock.onopen = () => {
            console.log('webSocket连接成功');
            state.wsStatus = true
            state.webSock.set;
           
            if(state.token || token) { //绑定操作
              let dataval = { messageType:0, extendField: state.token || token }
              let jsonData = JSON.stringify(dataval)
              state.webSock.send(jsonData);
            }

            state.timer = setInterval(() => {
                state.webSock.send('PING');
            }, 3000);


            state.webSock.onmessage = (event) => {
                console.log("接收消息", event.data);
                
                if(event && event.data!='PONG') {
                  let data = JSON.parse(event.data)
                  if(data.sendMessage && data.sendMessage.assistantMessage==null && data.sendMessage.messageContent=="绑定失败") {
                    console.log("绑定失败", state.token)
                    setTimeout(() => {
                      let dataValue = { messageType:0, extendField: state.token || token }
                      let jsonData = JSON.stringify(dataValue)
                      state.webSock.send(jsonData);
                    }, 4000);
                  }
                  let obj = data.sendMessage.assistantMessage || null
                  if(!obj) return
                  if(obj.contentType<=3) {
                    if(router.currentRoute.path=="/services/index" && state.currentChat && state.currentChat.userId == obj.userId) {
                      state.history.push(obj)
                      state.chatting.forEach(element => {
                        if(element.userId == obj.userId) {
                          let arr = ["", obj.content, "【图片】", "【视频】", "【商品】", "【订单】", "【售后单】"]
                          element.lastMessageContent = arr[obj.contentType]
                          element.lastMessageTime = obj.createTime
                        }
                      });
                      state.random = Math.random()
                    }else if(router.currentRoute.path!="/services/index" && state.currentChat && state.currentChat.userId == obj.userId) {
                      dispatch("getChatting")
                      setTimeout(()=>{
                        dispatch("getHistory", {
                          conversationId: state.currentChat.id, // 会话ID
                          page: 1, //页码
                          limit: 50, //每页数量
                        })
                      }, 0)
                    }else{
                      dispatch("getChatting")
                    }
                  }else if(obj.contentType==31) {
                    dispatch("getChatting")
                  }else if(obj.contentType==21) {
                    dispatch("getChatting")
                  }else{
                    let contentObj = JSON.parse(obj.content)
                    let info = {
                      contentObj: contentObj,
                      senderType: obj.senderType,
                      isAdminRead: obj.isAdminRead,
                      isUserRead: obj.isUserRead,
                      contentType: obj.contentType,
                      createTime: obj.createTime,
                      userId: obj.userId
                    }
                    if(router.currentRoute.path=="/services/index" && state.currentChat && state.currentChat.userId == info.userId) {
                      state.history.push(info)
                      state.chatting.forEach(element => {
                        if(element.userId == obj.userId) {
                          let arr = ["", obj.content, "【图片】", "【视频】", "【商品】", "【订单】", "【售后单】"]
                          element.lastMessageContent = arr[obj.contentType]
                          element.lastMessageTime = obj.createTime
                        }
                      });
                      state.random = Math.random()
                    }else{
                      dispatch("getChatting")
                    }
                  }
                }
             };
        };
        state.webSock.onerror = (err) => {
          console.log('webSocket连接错误');
            console.log(err);
            state.wsStatus = false
        };

        state.webSock.onclose = (e) => {
            state.wsStatus = false
            console.log('webSocket连接关闭');
            clearInterval(state.timer);
            state.timer = null;
            state.webSock.close();
            state.lockReconnect = false;
            dispatch("reconnect")
            console.log(router.currentRoute.name==="ServicesIndex")
            let isChatting = router.currentRoute.name==="ServicesIndex"
            if(isChatting && !state.currentChat.id) {
              dispatch("getChatting")
            }

            if(isChatting && state.currentChat && state.currentChat.id) {
              dispatch("getHistory", {
                conversationId: state.currentChat.id, // 会话ID
                page: 1, //页码
                limit: 50, //每页数量
              } )
              setTimeout(()=>{
                dispatch("getChatting")
              }, 0)
              
            }
        };
    },
    // 断开重连操作
    reconnect({ commit, state, dispatch }) {
        console.log("断开重连操作",  state.lockReconnect)
        if (state.lockReconnect) return;
        commit("SET_lockReconnect", true)
        setTimeout(() => {
            commit("SET_lockReconnect", false)
            dispatch("initwebsocket")
        }, 6000);
    },
};


export default {
    state,
    mutations,
    actions,
  };